﻿// ********************
//  作者：	沈琦
//  创建：	2016-03-24
//  注：状态机基础流程
// ********************
using UnityEngine;
using System.Collections;

public class FSM<T>
{
    private T stateEntity;
    private IFSMState<T> currentState;
    private IFSMState<T> previousState;
    private IFSMState<T> autoChangeState;

    public FSM(T inst)
    {
        stateEntity = inst;
        autoChangeState = null;
    }

    // for init FSM
    public void SetCurrentState(IFSMState<T> state)
    {
        currentState = state;
    }

    public void SetPreviousState(IFSMState<T> state)
    {
        previousState = state;
    }

    // called by T
    public void Update()
    {
        if (autoChangeState != null)
        {
            ChangeState(autoChangeState);
            autoChangeState = null;
            return;
        }
        if (currentState != null)
        {
            currentState.Execute(stateEntity);
        }
    }

    public void AutoChangeState(IFSMState<T> state)
    {
        autoChangeState = state;
    }

    public void ChangeState(IFSMState<T> state)
    {
        if (state == null)
        {
            //      Debug.LogError("The state would be switched is null");
            return;
        }
        autoChangeState = null;
        if (currentState != state)
        {
            previousState = currentState;
        }

        if (currentState != null)
        {
            currentState.Exit(stateEntity);
        }

        currentState = state;
        currentState.Enter(stateEntity);
    }

    public void RevertToPreviousState()
    {
        ChangeState(previousState);
    }

    public bool IsInState(IFSMState<T> state)
    {
        return currentState.GetType() == state.GetType();
    }

    public void Dispose()
    {
        currentState = null;
        previousState = null;
        autoChangeState = null;
    }
}
